﻿using System;
using System.Text;

namespace ConsoleApp1
{
    public class DigitConverter
    {
        private static readonly string _numbers = "0123456789abcdefghijklmnopqrstuvwxyz";
        private readonly int _radix;

        public DigitConverter(int radix = 36)
        {
            if (radix > 36)
            {
                throw new ArgumentOutOfRangeException(nameof(radix), "the radix is supported by the 36 max");
            }

            _radix = radix;
        }

        /// <summary>
        /// 转数字
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public long ConvertTo64(string number)
        {
            long result = 0;
            var len = number.Length;
            for (int i = 0; i < len; i++)
            {
                var n = StrToNumber(number[i]);
                var d = len - i - 1; // 高次减1
                var p = (long)Math.Pow(_radix, d);
                result += n * p;
            }
            return result;
        }


        public int ConvertTo32(string number)
        {
            return (int)ConvertTo64(number);
        }

        /// <summary>
        /// 转指定进制数值
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public string ConvertToDigit(long number)
        {
            StringBuilder sb = new StringBuilder(64);
            while (number > 0)
            {
                var remainder = (int)(number % _radix);
                number = number / _radix;
                sb.Insert(0, NumberToStr(remainder));
            }

            return sb.ToString();
        }

        private string NumberToStr(int number)
        {
            if (number >= _radix)
            {
                throw new ArgumentOutOfRangeException(nameof(number));
            }

            return _numbers[number].ToString();
        }

        private int StrToNumber(char num)
        {
            return _numbers.IndexOf(num);
        }
    }
}
